package pers.fulsun.blog.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.common.support.IController;
import net.dreamlu.mica.core.result.R;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pers.fulsun.blog.entity.Article;
import pers.fulsun.blog.entity.EsArticle;
import pers.fulsun.blog.service.ArticleService;

/**
 * 服务控制器
 *
 * @author fl
 * @since 2021-11-29 11:19:42
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/article")
public class ArticleController implements IController {
  private final ArticleService articleService;

  @RequestMapping(value = "/all", method = RequestMethod.GET)
  public Map<String, Object> getArticleByState(
      @RequestParam(value = "state", defaultValue = "-1") Integer state,
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "count", defaultValue = "6") Integer count,
      String keywords) {
    List<EsArticle> articles = articleService.getArticleByState(state, page, count, keywords);
    Map<String, Object> map = new HashMap<>();
    map.put("totalCount", 15);
    //    map.put("articles", articles.getRecords());
    map.put("articles", articles);
    return map;
  }

  @RequestMapping(value = "/", method = RequestMethod.POST)
  public R<String> addNewArticle(Article article) throws JsonProcessingException {
    boolean result = articleService.addNewArticle(article);
    if (result) {
      return success(article.getId() + "");
    } else {
      return fail(article.getIsdraft() == 1 ? "文章保存失败!" : "文章发表失败!");
    }
  }

  @RequestMapping(value = "/{aid}", method = RequestMethod.GET)
  public Article getArticleById(@PathVariable Long aid) {
    return articleService.getArticleById(aid);
  }
}
